import { BrowserHistory } from "history"
import * as  React from "react"
import { MicroAppContext } from "../context/MicroAppContext"
import MicroApp from "../core/MicroApp"
import useActiveEntry from "./useActiveEntry"
import { debug } from "../utils/log"




const useMicroApp = (props?:any) => {
  debug('**************************')
  const [loading, setLoading] = React.useState(false);
  const {publicPath,spin} = React.useContext(MicroAppContext)
  const { route } = useActiveEntry()
  // const [route, setRoute] = React.useState<{ [key: string]: any }>({});
  const [element, setElement] = React.useState<any>(null)
  // React.useEffect(() => {
  //   matchActiveApp()
  // }, [routes])
  // const matchActiveApp = () => {


  //   // let item = findActiveEntry(routes, window.location.pathname, basename as string)

  //   if (!item) {
  //     item = {
  //       name: '404',
  //       entry: '/pages/404.js'
  //     }
  //   }

  //   if (item.MicroApp) {
  //     const { MicroApp } = item
  //     setElement(<MicroApp onLoad={() => {
  //       setLoading(false);
  //     }} {...item} />)
  //   } else {

  //     setElement(<MicroApp onLoad={() => setLoading(false)} publicPath={publicPath} {...item} />)
  //   }
  //   setRoute(item)
  // }
  // React.useEffect(() => {
  //   const unlisten = (history as BrowserHistory).listen(() => {
  //     // matchActiveApp()
  //   })
  //   return () => {
  //     unlisten()
  //   }
  // }, [])
  const onLoad = ()=>{
  setLoading(false)
  }
  React.useEffect(() => {
   
    debug('routeroute', route)
    if (route) {
     setLoading(true)
      if (route.MicroApp) {
        const { MicroApp } = route
        setElement(<MicroApp  {...route} />)
      } else if(route.entry){

        setElement(<MicroApp appProps={props} spin={spin} publicPath={publicPath}  {...route} />)
      }else(
        setElement(null)
      )
      // setElement(<MicroApp onLoad={() => setLoading(false)} {...route} />)
    }
  }, [route])
 debug('useMicroApp',route.path,loading,publicPath,element)
  return {
    route,
    loading,
    element
  }
}
export default useMicroApp